﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EF;
using BL;
using BL.Entities;
using ApriBox.Mvc.UploadHelpers;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;

namespace ApriBox.Mvc.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/
        FSEntitiesRepository repository = new FSEntitiesRepository();            
        
        public ActionResult Upload()
        {
            return PartialView();
        }

        [HttpPost]
        [Authorize]
        public void Upload(HttpPostedFileBase file, int folderId)
        {

            if ((repository.GetAllowedCapacity(HttpContext.User.Identity.Name) - repository.GetStorageCapacity(HttpContext.User.Identity.Name) - file.ContentLength/1024/1024)>0)
            {
            //путь записи файлов
                string mainPath = Server.MapPath(WebConfigurationManager.AppSettings["physicalPath"]);


            if (file != null && file.ContentLength > 0)
            {

                string entityFileName = file.FileName;                

                IEnumerable<File> filesList = repository.GetFiles(folderId);
                foreach (var f in filesList)
                {
                    if (f.Name == entityFileName)
                        entityFileName = Name.ChangeName(entityFileName, "file");
                }

                // сохраняем файл
                string actualPath = System.IO.Path.Combine(mainPath, getHashName(entityFileName));
                try
                {
                    file.SaveAs(actualPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                        Console.WriteLine(ex.StackTrace);
                    }
                }

                // создаем сущность для БД
                repository.WriteFiles(new File
                {
                    Name = entityFileName,
                    ParentId = folderId,
                    PhysicalPath = actualPath,
                    DateCreate = DateTime.Now.Date,
                    DateUpdate = DateTime.Now.Date,
                    Owner = HttpContext.User.Identity.Name,
                    Size = file.ContentLength,
                    Extension = file.ContentType,
                    Icon = SetIcon(entityFileName.Split('.').Last())
                });
                repository.IncrimentStorageCapacity(file.ContentLength, HttpContext.User.Identity.Name);

            }
            }
            


        }

        //генерируем имя файла для фс
        string getHashName(string fileName)
        {
            StringBuilder strb = new StringBuilder();
            strb.Append(DateTime.Now.Ticks);
            strb.Append(HttpContext.User.Identity.Name.GetHashCode());
            strb.Append(fileName.GetHashCode());
            strb.Append(".");
            strb.Append(fileName.Split('.').Last());

            return  strb.ToString();
        }

        string SetIcon(string ext) 
        {
            string iconPath;
            if(Regex.IsMatch("_blank _page aac ai aiff avi bmp cs cpp css dat dmg doc dotx dwg dxf"+ 
                                "eps exe flv gif hhpp html ics iso java jpg js key less mid mp3 mp4"+
                                    "mpg odf ods odt otp ots ott pdf php png ppt psd py qt rar rb rtf sass scss"+
                                        "sql tga tgz tiff txt wav xls xlsx xml yml zip","\\b"+ext+"\\b"))
                iconPath = "/Content/icons/"+ext+".png";
            else iconPath = "/Content/file150.png";
            return iconPath;
        }
    }
}
